﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.HttpClients;
using System.Configuration;
using System.Data.SqlClient;
using In.Api.Dto.HisWs;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnpickupingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnpickupingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnpickupingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel, msg.Reason);
                    }
                   

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(500);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel, int reason = 2)
        {
            OrderSummary order;
            using (var ctx = new HzfyWeiXinEntities())
            {
                order = ctx.ApptOrder.Where(x => x.Id == orderId)
                    .Select(x => new OrderSummary
                    {
                        Id = x.Id,
                        OrderNo = x.OrderNo,
                        SumFee = x.SumFee
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

                //order.OrderStatus = ApptOrderExtensions.OrderStatus.微信退号中.ToInt32();
                //ctx.SaveChanges();
                using (var _ctx = new HzfyWeiXinEntities())
                {
                    SqlParameter[] para =
                    {
                        new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.微信退号中.ToInt32()),
                        new SqlParameter("@OrderId", order.Id),
                    };
                    _ctx.Database.ExecuteSqlCommand(
                        "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                }
            }


            //执行退号操作
            var unpickupRequest = new Request4CancelAppoint();
            unpickupRequest.OrderId = order.OrderNo;
            Response4CancelAppoint unpickupResponse;

            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/CancelAppoint", unpickupRequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                unpickupResponse = responseMsg.Content.ReadAsAsync<Response4CancelAppoint>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内退号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                // RMQ 执行退号结果查询
                var unpickupingChkProducer = new OrderUnpickupingChkProducer();
                unpickupingChkProducer.Publish(new OrderUnpickupingChkMsg
                {
                    OrderType = Rmq.Center.OrderType.挂号订单,
                    OrderId = order.Id
                }, 5 * 60 * 1000);

                return new ConsumedResult
                {
                    Ack = true
                };
            }
            finally
            {
                // RMQ 取消锁号
                var unlockingProducer = new OrderUnlockingProducer();
                unlockingProducer.Publish(new OrderUnlockingMsg
                {
                    OrderType = OrderType.挂号订单,
                    OrderId = order.Id
                });
            }

            if (unpickupResponse.ResultCode != "0")
            {
                //order.OrderStatus = ApptOrderExtensions.OrderStatus.微信退号失败.ToInt32();
                //order.Remark = unpickupResponse.ResultDesc;
                //ctx.SaveChanges();
                using (var _ctx = new HzfyWeiXinEntities())
                {
                    SqlParameter[] para =
                    {
                        new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.微信退号失败.ToInt32()),
                        new SqlParameter("@Remark", unpickupResponse.ResultDesc),
                        new SqlParameter("@OrderId", order.Id),
                    };
                    _ctx.Database.ExecuteSqlCommand(
                        "Update ApptOrder set OrderStatus= @OrderStatus,Remark=@Remark where Id=@OrderId", para);
                }


                // RMQ 发送退号失败的用户通知
                var msgProducer = new UserMessageProducer();
                msgProducer.Publish(new UserMessageMsg
                {
                    Type = UserMessageType.退号失败通知,
                    OrderId = order.Id
                });
            }
            else
            {
                //order.OrderStatus = ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32(); 
                ////order.RefundOperator = reason; 
                //ctx.SaveChanges();

                using (var _ctx = new HzfyWeiXinEntities())
                {
                    SqlParameter[] para =
                    {
                        new SqlParameter("@OrderStatus", ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32()),
                        new SqlParameter("@OrderId", order.Id),
                    };
                    _ctx.Database.ExecuteSqlCommand(
                        "Update ApptOrder set OrderStatus= @OrderStatus where Id=@OrderId", para);
                }

                // RMQ 发送退号成功的用户通知
                var msgProducer = new UserMessageProducer();
                msgProducer.Publish(new UserMessageMsg
                {
                    Type = UserMessageType.退号成功通知,
                    OrderId = order.Id
                });

                if (order.SumFee > 0)
                {
                    // RMQ 执行退费操作
                    var refundingProducer = new OrderRefundingUnpickupSucceedProducer();
                    refundingProducer.Publish(new OrderRefundingUnpickupSucceedMsg
                    {
                        OrderType = Rmq.Center.OrderType.挂号订单,
                        OrderId = order.Id
                    });
                }
            }


            return new ConsumedResult
            {
                Ack = true
            };
        }

        public class OrderSummary
        {
            public int Id { get; set; }
            public string OrderNo { get; set; }
            public decimal? SumFee { get; set; }
        }
    }
}